package org.artifact.core.actor;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import co.paralleluniverse.actors.ActorRef;
import co.paralleluniverse.actors.behaviors.ServerHandler;
import co.paralleluniverse.fibers.SuspendExecution;

/**
 * Actor消息处理器
 */
public class ActorHandler implements ServerHandler<ICallable, Object, IRunnable> {

    private static final Log log = LogFactory.get(ActorHandler.class);

    @Override
    public Object handleCall(ActorRef<?> from, Object id, ICallable m) throws InterruptedException, SuspendExecution {
        return m.call();
    }

    @Override
    public void handleCast(ActorRef<?> from, Object id, IRunnable m) throws SuspendExecution {
        try {
            m.run();
        } catch (Exception e) {
            log.error(e);
        }
    }

    @Override
    public void handleInfo(Object m) throws SuspendExecution {
        if (m instanceof IRunnable) {
            try {
                ((IRunnable) m).run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void handleTimeout() throws SuspendExecution {
        log.info("handleTimeout");
    }

    @Override
    public void init() throws InterruptedException, SuspendExecution {
        log.info("init");
    }

    @Override
    public void terminate(Throwable cause) throws SuspendExecution {
        log.info("terminate = {}", cause);
    }
}
